package controller;

import databaseLayer.CustomerUpdate;
import java.util.Vector;
import java.util.logging.Level;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 *
 * @author Sam
 */
public class PurchaseListener implements HttpSessionAttributeListener, Runnable {
    private Vector<Thread> clock = new Vector();
    private Vector<String> recordID = new Vector();
    private int sleepThread;
    private int stoppedThread;
    
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (event.getName() != null && event.getName().equals("unpaidRecordID")) {
            String thisRecordID = (String)event.getValue();
            int thisIndex;
            
            synchronized(this) {
                thisIndex = clock.size();
                clock.addElement(new Thread(this));
                recordID.addElement(thisRecordID);
            }
            
            clock.elementAt(thisIndex).start();
        }
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {}

    public void attributeReplaced(HttpSessionBindingEvent event) {}

    public void run() {
        try {
            int sleepIndex;
            
            synchronized(this) {
                sleepIndex = sleepThread;
                sleepThread++;
            }
            
            clock.elementAt(sleepIndex).sleep(5*60*1000);
            
            synchronized(this) {
                stoppedThread++;
            }
            
            String currentRecordID = recordID.elementAt(sleepIndex);
            if (!CustomerUpdate.isPurchasePaid(currentRecordID)) {
                CustomerUpdate.timeOutPurchase(currentRecordID);
            }
            
            clock.elementAt(sleepIndex).stop();
            
            synchronized(this) {
                if (sleepThread != 0 && clock.size() == stoppedThread) {
                    clock.removeAllElements();
                    recordID.removeAllElements();
                    sleepThread = 0;
                    stoppedThread = 0;
                }
            }
        }
        catch (InterruptedException ex) {
            java.util.logging.Logger.getLogger(PurchaseListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
